#import "YQMYBaseNavigationController.h"
#import "MYLoginVC.h"
#import "YQPNetWorkingManager.h"
#import "YQPNetWorkingBaseModel.h"
#import "YQInterfaceDocument.h"
//#import "YQPensionDoctorLoginVC.h"
//#import "YQBaseNavgationViewController.h"
#define kShowSuccess @"需要登陆才能查看或使用该功能"
static AFHTTPSessionManager *manager = nil;

@implementation YQPNetWorkingManager

//在此方法中加入SSL证书
+ (AFHTTPSessionManager *)sharedAFManager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [[AFHTTPResponseSerializer alloc] init];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript",@"text/plain", nil];
    });
    return manager;
}

+ (void)sendGetRequest:(NSString *)url
            parameters:(NSDictionary *)parameters
               success:(void (^)(YQPNetWorkingBaseModel *responseObject))success
               failure:(void (^)(NSUInteger statusCode,NSString *error))failure
{
    [YQPNetWorkingManager sendGetRequest:url
                    parameters:parameters
                       success:success
                       failure:failure
                     parseData:NO];
}

+ (void)sendGetRequest:(NSString *)url
            parameters:(NSDictionary *)parameters
               success:(void (^)(YQPNetWorkingBaseModel * responseObject))success
               failure:(void (^)(NSUInteger statusCode,NSString *error))failure
             parseData:(BOOL)parseData;
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    });
    
    NSString *urlStr;
    
    if ([url containsString:@"http"]) {
        urlStr = url;
    }
    else {
        urlStr = [NSString stringWithFormat:@"%@%@",kApphttp,url];
    }
    
    [self sharedAFManager].requestSerializer.timeoutInterval = 10.f;
    [self sharedAFManager].requestSerializer = [AFJSONRequestSerializer serializer];
    
    NSString *token = [YQPUserTool account].token;
    NSLog(@"--token: %@",token);
    [[self sharedAFManager].requestSerializer setValue:token forHTTPHeaderField:@"token"];

    [[self sharedAFManager] GET:urlStr parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        });
        
        NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        //登录过期
        if ([dict isKindOfClass:[NSDictionary class]]) {
            
            if ([[dict objectForKey:@"code"] intValue] == 1000) {
                [MBProgressHUD showSuccess:kYQLS(kShowSuccess)];

                MYLoginVC *loginVc = [[MYLoginVC alloc] init];
                YQMYBaseNavigationController *navVC = [[YQMYBaseNavigationController alloc] initWithRootViewController:loginVc];
                [UIApplication sharedApplication].keyWindow.rootViewController = navVC;
                 
            }
            
//            if ([[dict objectForKey:@"code"] intValue] == 500){
//                [MBProgressHUD showSuccess:dict[@"msg"]];
//                return ;
//            }
            
//            if ([[dict objectForKey:@"code"] intValue] != 0){
//                [MBProgressHUD showSuccess:dict[@"msg"]];
//                return ;
//            }
        }
        
        YQPNetWorkingBaseModel *baseModel = [YQPNetWorkingBaseModel modelWithJSON:dict];
        NSLog(@"%@ --- %@",urlStr,dict);
        if (parseData)
        {
            [YQPNetWorkingManager parseServerDataWithSessionDataTask:task
                                            responseObject:dict
                                                  finished:^(BOOL successed, id serverData, NSString *errorCode, NSString *errorMessage)
             {
                 if (success) {
                     if (success) {
                         
                         success(serverData);
                     }
                 }
                 else
                 {
                     if (failure) {
                         failure([errorCode integerValue],errorMessage);
                     }
                 }
                 
             }];
        }
        else
        {
            if (!responseObject) {
                NSInteger errorCode = 6001;
                NSString *tError = [NSString stringWithFormat:@"%@(N%ld)",kYQLS(@"系统繁忙，请稍后再试"),(long)errorCode];
                if (failure) {
                    failure(errorCode,tError);
                }
            } else {
                
                if (success) {
                    success(baseModel);
                }
            }
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@ = error= %zd === %@",urlStr,[error code],[error localizedDescription]);
        NSString *tError = nil;
        switch ([error code]) {
            case NSURLErrorTimedOut:
                tError = kYQLS(@"连接服务器超时，请检查你的网络或稍后重试");
                break;
            case NSURLErrorBadURL:
            case NSURLErrorUnsupportedURL:
            case NSURLErrorCannotFindHost:
            case NSURLErrorDNSLookupFailed:
            case NSURLErrorCannotConnectToHost:
            case NSURLErrorNetworkConnectionLost:
            case NSURLErrorNotConnectedToInternet:
            case NSURLErrorUserAuthenticationRequired:
            case NSURLErrorUserCancelledAuthentication:
            case NSURLErrorSecureConnectionFailed:
            case NSURLErrorServerCertificateHasBadDate:
            case NSURLErrorServerCertificateHasUnknownRoot:
            case NSURLErrorServerCertificateNotYetValid:
            case NSURLErrorServerCertificateUntrusted:
            case NSURLErrorClientCertificateRejected:
            case NSURLErrorClientCertificateRequired:
                tError = kYQLS(@"无法连接到服务器，请检查你的网络或稍后重试");
                break;
            case NSURLErrorHTTPTooManyRedirects:
                tError = kYQLS(@"太多HTTP重定向，请检查你的网络或稍后重试");
                break;
                
            default:
                tError = kYQLS(@"系统繁忙，请稍后再试");
                [MBProgressHUD showMessage:tError];

                break;
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        });
        
        if (failure) {
            failure([error code],tError);
        }
    }];
}


+ (void)sendGetRequestToWeChat:(NSString*)url
                    parameters:(id)parameters
                       success:(void (^)(id responseObject))success
                       failure:(void (^)(NSError* error))failure
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    });
    [self sharedAFManager].requestSerializer.timeoutInterval = 10.f;
    [self sharedAFManager].requestSerializer = [AFJSONRequestSerializer serializer];
    [[self sharedAFManager] GET:url parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        success(dict);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
}

#pragma mark - 网络请求-Post方式
+ (void)sendPostRequest:(NSString *)url
             parameters:(id)parameters
                success:(void (^)(YQPNetWorkingBaseModel *responseObject))success
                failure:(void (^)(NSUInteger statusCode,NSString *error))failure
{
    [YQPNetWorkingManager sendPostRequest:url
                     parameters:parameters
                        success:success
                        failure:failure
                      parseData:NO];
}

+ (void)sendPostRequest:(NSString *)url
             parameters:(id)parameters
                success:(void (^)(YQPNetWorkingBaseModel *responseObject))success
                failure:(void (^)(NSUInteger statusCode,NSString *error))failure
              parseData:(BOOL)parseData;
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    });
    
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",kApphttp,url];
    
    [self sharedAFManager].requestSerializer.timeoutInterval = 10.f;
    [self sharedAFManager].requestSerializer = [AFJSONRequestSerializer serializer];
    NSString *token = [YQPUserTool account].token;
    [[self sharedAFManager].requestSerializer setValue:token forHTTPHeaderField:@"token"];
    NSLog(@"--token: %@",token);
    [[self sharedAFManager] POST:urlStr parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        });
        
        NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        //登录过期
        if ([dict isKindOfClass:[NSDictionary class]]) {
            
            if ([[dict objectForKey:@"code"] intValue] == 1000) {
                [MBProgressHUD showSuccess:kYQLS(kShowSuccess)];
                YQHIDELOADINGTIPS
                MYLoginVC *loginVc = [[MYLoginVC alloc] init];
                YQMYBaseNavigationController *navVC = [[YQMYBaseNavigationController alloc] initWithRootViewController:loginVc];
                [UIApplication sharedApplication].keyWindow.rootViewController = navVC;
                 
            }

        }
                
        YQPNetWorkingBaseModel *baseModel = [YQPNetWorkingBaseModel modelWithJSON:dict];
        NSLog(@"%@ --- %@",urlStr,dict);
        if (parseData)
        {
            [YQPNetWorkingManager parseServerDataWithSessionDataTask:task
                                            responseObject:dict
                                                  finished:^(BOOL successed, id serverData, NSString *errorCode, NSString *errorMessage)
             {
                 if (success && [[dict objectForKey:@"code"] intValue] == 0) {
                     if (success) {
                         success(serverData);
                     }
                 }
                 else
                 {
                     if (failure) {
                         failure([errorCode integerValue],errorMessage);
                     }
                 }
             }];
        }
        else
        {
            if (!responseObject) {
                NSInteger errorCode = 6001;
                NSString *tError = [NSString stringWithFormat:@"%@(N%ld)",kYQLS(@"系统繁忙，请稍后再试"),(long)errorCode];
                if (failure) {
                    failure(errorCode,tError);
                }
            } else {
                if (success) {
                    success(baseModel);
                }
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"urlStr：%@ ---",urlStr);
        NSLog(@" error === %@",[error localizedDescription]);
        NSString *tError = nil;
        switch ([error code]) {
            case NSURLErrorTimedOut:
                tError = kYQLS(@"连接服务器超时，请检查你的网络或稍后重试");
                break;
            case NSURLErrorBadURL:
            case NSURLErrorUnsupportedURL:
            case NSURLErrorCannotFindHost:
            case NSURLErrorDNSLookupFailed:
            case NSURLErrorCannotConnectToHost:
            case NSURLErrorNetworkConnectionLost:
            case NSURLErrorNotConnectedToInternet:
            case NSURLErrorUserAuthenticationRequired:
            case NSURLErrorUserCancelledAuthentication:
            case NSURLErrorSecureConnectionFailed:
            case NSURLErrorServerCertificateHasBadDate:
            case NSURLErrorServerCertificateHasUnknownRoot:
            case NSURLErrorServerCertificateNotYetValid:
            case NSURLErrorServerCertificateUntrusted:
            case NSURLErrorClientCertificateRejected:
            case NSURLErrorClientCertificateRequired:
                tError = kYQLS(@"无法连接到服务器，请检查你的网络或稍后重试");
                break;
            case NSURLErrorHTTPTooManyRedirects:
                tError = kYQLS(@"太多HTTP重定向，请检查你的网络或稍后重试");
                break;
                
            default:
                tError = kYQLS(@"系统繁忙，请稍后再试");
                [MBProgressHUD showMessage:tError];
                YQHIDELOADINGTIPS
                break;
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        });
        
        if (failure) {
            failure([error code],tError);
        }
    }];
}

/// post form
+ (id)sendPOSTWithForm:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void (^)(YQPNetWorkingBaseModel *responseObject))success failure:(void (^)(NSUInteger statusCode,NSString *error))failure {
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    });
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",kApphttp,URLString];
    
    return [[self sessionManagerForm] POST:urlStr parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",URLString);
        dispatch_async(dispatch_get_main_queue(), ^{
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        });
        id dict =[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        //登录过期
        if ([dict isKindOfClass:[NSDictionary class]]) {
                
                if ([[dict objectForKey:@"code"] intValue] == 205 || [[dict objectForKey:@"code"] intValue] == 204) {
                    [MBProgressHUD showSuccess:kYQLS(kShowSuccess)];
                    YQHIDELOADINGTIPS
                    MYLoginVC *loginVc = [[MYLoginVC alloc] init];
                    YQMYBaseNavigationController *navVC = [[YQMYBaseNavigationController alloc] initWithRootViewController:loginVc];
                    [UIApplication sharedApplication].keyWindow.rootViewController = navVC;
                     
                }
            }
        
        YQPNetWorkingBaseModel *baseModel = [YQPNetWorkingBaseModel modelWithJSON:dict];
        
        if (success) {
            success(baseModel);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"urlStr：%@ ---",urlStr);
        NSLog(@" error === %@",[error localizedDescription]);
        NSString *tError = nil;
        switch ([error code]) {
            case NSURLErrorTimedOut:
                tError = kYQLS(@"连接服务器超时，请检查你的网络或稍后重试");
                break;
            case NSURLErrorBadURL:
            case NSURLErrorUnsupportedURL:
            case NSURLErrorCannotFindHost:
            case NSURLErrorDNSLookupFailed:
            case NSURLErrorCannotConnectToHost:
            case NSURLErrorNetworkConnectionLost:
            case NSURLErrorNotConnectedToInternet:
            case NSURLErrorUserAuthenticationRequired:
            case NSURLErrorUserCancelledAuthentication:
            case NSURLErrorSecureConnectionFailed:
            case NSURLErrorServerCertificateHasBadDate:
            case NSURLErrorServerCertificateHasUnknownRoot:
            case NSURLErrorServerCertificateNotYetValid:
            case NSURLErrorServerCertificateUntrusted:
            case NSURLErrorClientCertificateRejected:
            case NSURLErrorClientCertificateRequired:
                tError = kYQLS(@"无法连接到服务器，请检查你的网络或稍后重试");
                break;
            case NSURLErrorHTTPTooManyRedirects:
                tError = kYQLS(@"太多HTTP重定向，请检查你的网络或稍后重试");
                break;
                
            default:
                tError = kYQLS(@"系统繁忙，请稍后再试");
                [MBProgressHUD showMessage:tError];
                YQHIDELOADINGTIPS
                break;
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        });
        
        if (failure) {
            failure([error code],tError);
        }
    }];
}

+ (void)POSTWithForm:(NSString *_Nullable)URLString parameters:(id)parameters
success:(void (^)(YQPNetWorkingBaseModel *responseObject))success
         failure:(void (^)(NSUInteger statusCode,NSString *error))failure
{
    [self POSTWithForm:URLString parameters:parameters success:success failure:failure parseData:NO];
}

/// 表单提交字段2
+ (void)POSTWithForm:(NSString *_Nullable)URLString parameters:(id)parameters
    success:(void (^)(YQPNetWorkingBaseModel *responseObject))success
             failure:(void (^)(NSUInteger statusCode,NSString *error))failure
           parseData:(BOOL)parseData;
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    });
    
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",kApphttp,URLString];
    
    [self sessionManagerForm].requestSerializer.timeoutInterval = 10.f;
    
    [[self sharedAFManager] POST:urlStr parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        });
        
        NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        //登录过期
        if ([dict isKindOfClass:[NSDictionary class]]) {
//            if ([[dict objectForKey:@"code"] intValue] != 0) {
//                [MBProgressHUD showSuccess:dict[@"msg"]];
//                YQHIDELOADINGTIPS
//                return ;
//            }
            
            if ([[dict objectForKey:@"code"] intValue] == 401 || [[dict objectForKey:@"code"] intValue] == 1000) {
                /*
                YQPensionDoctorLoginVC *loginVc = [[YQPensionDoctorLoginVC alloc] init];
                YQBaseNavgationViewController *navVC = [[YQBaseNavgationViewController alloc] initWithRootViewController:loginVc];
                [UIApplication sharedApplication].keyWindow.rootViewController = navVC;
                 */
            }
        }
        
        //10002  该账号已被停用 --- --- 注册过的号码在此处注册会崩溃
        if ([dict isKindOfClass:[NSDictionary class]]) {
            if ([[dict objectForKey:@"info"] intValue] == 10002 && ![[dict objectForKey:@"msg"] containsString:@"注册"]) {
                /*
                //[[NSNotificationCenter defaultCenter] postNotificationName:@"CH_LOGIN_STOP_NOTIFICATION" object:nil];
                YQPensionDoctorLoginVC *loginVc = [[YQPensionDoctorLoginVC alloc] init];
                YQBaseNavgationViewController *navVC = [[YQBaseNavgationViewController alloc] initWithRootViewController:loginVc];
                [UIApplication sharedApplication].keyWindow.rootViewController = navVC;
                 */
            }
        }
        YQPNetWorkingBaseModel *baseModel = [YQPNetWorkingBaseModel modelWithJSON:dict];
        NSLog(@"%@ --- %@",urlStr,dict);
        if (parseData)
        {
            [YQPNetWorkingManager parseServerDataWithSessionDataTask:task
                                            responseObject:dict
                                                  finished:^(BOOL successed, id serverData, NSString *errorCode, NSString *errorMessage)
             {
                 if (success) {
                     if (success) {
                         success(serverData);
                     }
                 }
                 else
                 {
                     if (failure) {
                         failure([errorCode integerValue],errorMessage);
                     }
                 }
             }];
        }
        else
        {
            if (!responseObject) {
                NSInteger errorCode = 6001;
                NSString *tError = [NSString stringWithFormat:@"%@(N%ld)",kYQLS(@"系统繁忙，请稍后再试"),(long)errorCode];
                if (failure) {
                    failure(errorCode,tError);
                }
            } else {
                if (success) {
                    success(baseModel);
                }
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@ ---",urlStr);
        NSLog(@" error === %@",[error localizedDescription]);
        NSString *tError = nil;
        switch ([error code]) {
            case NSURLErrorTimedOut:
                tError = kYQLS(@"连接服务器超时，请检查你的网络或稍后重试");
                break;
            case NSURLErrorBadURL:
            case NSURLErrorUnsupportedURL:
            case NSURLErrorCannotFindHost:
            case NSURLErrorDNSLookupFailed:
            case NSURLErrorCannotConnectToHost:
            case NSURLErrorNetworkConnectionLost:
            case NSURLErrorNotConnectedToInternet:
            case NSURLErrorUserAuthenticationRequired:
            case NSURLErrorUserCancelledAuthentication:
            case NSURLErrorSecureConnectionFailed:
            case NSURLErrorServerCertificateHasBadDate:
            case NSURLErrorServerCertificateHasUnknownRoot:
            case NSURLErrorServerCertificateNotYetValid:
            case NSURLErrorServerCertificateUntrusted:
            case NSURLErrorClientCertificateRejected:
            case NSURLErrorClientCertificateRequired:
                tError = kYQLS(@"无法连接到服务器，请检查你的网络或稍后重试");
                break;
            case NSURLErrorHTTPTooManyRedirects:
                tError = kYQLS(@"太多HTTP重定向，请检查你的网络或稍后重试");
                break;
                
            default:
                tError = kYQLS(@"系统繁忙，请稍后再试");
                [MBProgressHUD showMessage:tError];

                break;
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        });
        
        if (failure) {
            failure([error code],tError);
        }
    }];
}

+ (AFHTTPSessionManager *)sessionManagerForm {
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];

    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/plain", @"text/javascript", @"text/xml", @"image/*",@"text/encode", nil];
    NSString *token = [YQPUserTool account].token;
    NSLog(@"--token: %@",token);
    [sessionManager.requestSerializer setValue:token?:@"" forHTTPHeaderField:@"token"];
    if (token.length >  0) {
        [sessionManager.requestSerializer setValue:token forHTTPHeaderField:@"token"];
    }
    return sessionManager;
}


#pragma mark - Private Function
+ (void)parseServerDataWithSessionDataTask:(NSURLSessionDataTask*)operation responseObject:(id)responseObject finished:(queryResultHandle)completedHandle;
{
    NSHTTPURLResponse *operationResponse = (NSHTTPURLResponse *)(operation.response);
    
    [self parseServerDataWithSessionHttpURLResponse:operationResponse responseObject:responseObject finished:completedHandle];
}


+ (void)parseServerDataWithSessionHttpURLResponse:(NSHTTPURLResponse *)httpURLResponse responseObject:(id)responseObject finished:(queryResultHandle)completedHandle
{
    if (200 == httpURLResponse.statusCode)
    {
        if (responseObject)
        {
            if ([responseObject isKindOfClass:[NSDictionary class]])
            {
                //使用最新的数据解析方式，防止数据结构变更导致crash
                BOOL isSuccess = [[((NSDictionary *)responseObject) getNSNumberObjectForKey:@"status"] boolValue];
                long long codeValue = [[((NSDictionary *)responseObject) getNSNumberObjectForKey:@"code"] longLongValue];
                NSString* errorCode = [NSString stringWithFormat:@"%ld",(long)codeValue];
                NSString* errorMessage = [((NSDictionary *)responseObject) getNSStringObjectForKey:@"message"];
                id serverData = [((NSDictionary *)responseObject) getObjectForKey:@"data"];
                
                if (completedHandle)
                {
                    completedHandle(isSuccess, serverData, errorCode, errorMessage);
                }
            }
            else
            {
                //@"服务器返回的json格式错误"
                NSString* errorCode = @"6001";
                NSString* errorMessage = kYQLS(@"系统繁忙，请稍后再试");
                
                NSLog(@"网络状态码【%ld】开发错误码【%@】URL【%@】responseObject类名【%@】responseObject内容【%@】", (long)httpURLResponse.statusCode, errorCode, httpURLResponse.URL.absoluteString, NSStringFromClass([responseObject class]), responseObject);
                if (completedHandle)
                {
                    completedHandle(NO, nil, errorCode, errorMessage);
                }
            }
        }
        else
        {
            // @"服务器返回的数据为空"
            NSString* errorCode = @"6001";
            NSString* errorMessage = kYQLS(@"系统繁忙，请稍后再试");
            NSLog(@"网络状态码【%ld】开发错误码【%@】URL【%@】", (long)httpURLResponse.statusCode, errorCode, httpURLResponse.URL.absoluteString);
            if (completedHandle)
            {
                completedHandle(NO, nil, errorCode, errorMessage);
            }
        }
    }
    else
    {
        //@"服务器没有响应"
        NSString* errorCode = @"6001";
        NSString* errorMessage = kYQLS(@"系统繁忙，请稍后再试");
        if ([responseObject isKindOfClass:[NSError class]])
        {
            NSError* error = (NSError*)responseObject;
            if (error.code == NSURLErrorTimedOut)
            {
                errorCode = @"6001";
                errorMessage = kYQLS(@"网络超时");
            }
        }
        
        NSLog(@"网络状态码【%ld】开发错误码【%@】URL【%@】", (long)httpURLResponse.statusCode, errorCode, httpURLResponse.URL.absoluteString);
        if (completedHandle)
        {
            completedHandle(NO, nil, errorCode, errorMessage );
        }
    }
}


#pragma mark - 网络请求-Post+file方式

#pragma mark - 网络请求-Post+file方式 多图片
+ (void)sendPostRequests:(NSString *)url
parameters:(NSDictionary *)parameters
  fileDataArr:(NSArray <NSData *> *)fileDataArr
  fileName:(NSString *)fileName
   success:(void (^)(YQPNetWorkingBaseModel *responseObject))success
   failure:(void (^)(NSUInteger statusCode,NSString *error))failure {
    [YQPNetWorkingManager sendPostRequests:url
    parameters:parameters
      fileDataArr:fileDataArr
      fileName:fileName
       success:success
       failure:failure
     parseData:NO];
    
}

+ (void)sendPostRequests:(NSString *)url
             parameters:(NSDictionary *)parameters
               fileDataArr:(NSArray <NSData *> *)fileDataArr
               fileName:(NSString *)fileName
                success:(void (^)(YQPNetWorkingBaseModel *responseObject))success
                failure:(void (^)(NSUInteger statusCode,NSString *error))failure
              parseData:(BOOL)parseData;
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    });
    
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",kApphttp,url];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [[AFHTTPResponseSerializer alloc] init];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    manager.requestSerializer.timeoutInterval = 1000.f;
    
    NSString *token = [YQPUserTool account].token;
    [manager.requestSerializer setValue:token forHTTPHeaderField:@"token"];


    
    [manager POST:urlStr parameters:parameters headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (NSInteger i = 0; i < fileDataArr.count; i++) {
            NSData *fileData = fileDataArr[i];
            if (!IsNilOrNull(fileData)) {
                
                [formData appendPartWithFileData:fileData name:fileName fileName:[NSString stringWithFormat:@"%zd.png",i] mimeType:@"image/png"];
                
            }
        }
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        });
        
        NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        YQPNetWorkingBaseModel *baseModel = [YQPNetWorkingBaseModel modelWithJSON:dict];
        //        NSLog(@"%@ --- %@",urlStr,dict);
        if (parseData)
        {
            [YQPNetWorkingManager parseServerDataWithSessionDataTask:task
                                            responseObject:dict
                                                  finished:^(BOOL successed, id serverData, NSString *errorCode, NSString *errorMessage)
             {
                 if (success)
                 {
                     if (success)
                     {
                         success(serverData);
                     }
                 }
                 else
                 {
                     if (failure)
                     {
                         failure([errorCode integerValue],errorMessage);
                     }
                 }
                 
             }];
        }
        else
        {
            if (!responseObject) {
                NSInteger errorCode = 6001;//？？？？改变的。。。
                NSString *tError = [NSString stringWithFormat:@"%@(N%ld)",kYQLS(@"系统繁忙，请稍后再试"),(long)errorCode];
                if (failure) {
                    failure(errorCode,tError);
                }
            } else {
                if (success) {
                    success(baseModel);
                }
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@" error === %@",[error localizedDescription]);
        NSString *tError = nil;
        switch ([error code]) {
            case NSURLErrorTimedOut:
                tError = kYQLS(@"连接服务器超时，请检查你的网络或稍后重试");
                break;
            case NSURLErrorBadURL:
            case NSURLErrorUnsupportedURL:
            case NSURLErrorCannotFindHost:
            case NSURLErrorDNSLookupFailed:
            case NSURLErrorCannotConnectToHost:
            case NSURLErrorNetworkConnectionLost:
            case NSURLErrorNotConnectedToInternet:
            case NSURLErrorUserAuthenticationRequired:
            case NSURLErrorUserCancelledAuthentication:
            case NSURLErrorSecureConnectionFailed:
            case NSURLErrorServerCertificateHasBadDate:
            case NSURLErrorServerCertificateHasUnknownRoot:
            case NSURLErrorServerCertificateNotYetValid:
            case NSURLErrorServerCertificateUntrusted:
            case NSURLErrorClientCertificateRejected:
            case NSURLErrorClientCertificateRequired:
                tError = kYQLS(@"无法连接到服务器，请检查你的网络或稍后重试");
                break;
            case NSURLErrorHTTPTooManyRedirects:
                tError = kYQLS(@"太多HTTP重定向，请检查你的网络或稍后重试");
                break;
                
            default:
                tError = kYQLS(@"系统繁忙，请稍后再试");
                break;
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        });
        if (failure) {
            failure([error code],tError);
        }
    }];
}

+ (void)sendPostRequest:(NSString *)url
             parameters:(NSDictionary *)parameters
               fileData:(NSData *)fileData
               fileName:(NSString *)fileName
                success:(void (^)(id responseObject))success
                failure:(void (^)(NSUInteger statusCode,NSString *error))failure
{
    [YQPNetWorkingManager sendPostRequest:url
                     parameters:parameters
                       fileData:fileData
                       fileName:fileName
                        success:success
                        failure:failure
                      parseData:NO];
}
+ (void)sendPostRequest:(NSString *)url
             parameters:(NSDictionary *)parameters
               fileData:(NSData *)fileData
               fileName:(NSString *)fileName
                success:(void (^)(id responseObject))success
                failure:(void (^)(NSUInteger statusCode,NSString *error))failure
              parseData:(BOOL)parseData;
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    });
    
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",kApphttp,url];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [[AFHTTPResponseSerializer alloc] init];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    manager.requestSerializer.timeoutInterval = 1000.f;
    
    NSString *token = [YQPUserTool account].token;
    [manager.requestSerializer setValue:token forHTTPHeaderField:@"token"];


    
    [manager POST:urlStr parameters:parameters headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if (!IsNilOrNull(fileData)) {
            [formData appendPartWithFileData:fileData name:fileName fileName:@".png" mimeType:@"image/png"];
        }
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        });
        
        NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        //        NSLog(@"%@ --- %@",urlStr,dict);
        if (parseData)
        {
            [YQPNetWorkingManager parseServerDataWithSessionDataTask:task
                                            responseObject:dict
                                                  finished:^(BOOL successed, id serverData, NSString *errorCode, NSString *errorMessage)
             {
                 if (success)
                 {
                     if (success)
                     {
                         success(serverData);
                     }
                 }
                 else
                 {
                     if (failure)
                     {
                         failure([errorCode integerValue],errorMessage);
                     }
                 }
                 
             }];
        }
        else
        {
            if (!responseObject) {
                NSInteger errorCode = 6001;//？？？？改变的。。。
                NSString *tError = [NSString stringWithFormat:@"%@(N%ld)",kYQLS(@"系统繁忙，请稍后再试"),(long)errorCode];
                if (failure) {
                    failure(errorCode,tError);
                }
            } else {
                if (success) {
                    success(dict);
                }
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@" error === %@",[error localizedDescription]);
        NSString *tError = nil;
        switch ([error code]) {
            case NSURLErrorTimedOut:
                tError = kYQLS(@"连接服务器超时，请检查你的网络或稍后重试");
                break;
            case NSURLErrorBadURL:
            case NSURLErrorUnsupportedURL:
            case NSURLErrorCannotFindHost:
            case NSURLErrorDNSLookupFailed:
            case NSURLErrorCannotConnectToHost:
            case NSURLErrorNetworkConnectionLost:
            case NSURLErrorNotConnectedToInternet:
            case NSURLErrorUserAuthenticationRequired:
            case NSURLErrorUserCancelledAuthentication:
            case NSURLErrorSecureConnectionFailed:
            case NSURLErrorServerCertificateHasBadDate:
            case NSURLErrorServerCertificateHasUnknownRoot:
            case NSURLErrorServerCertificateNotYetValid:
            case NSURLErrorServerCertificateUntrusted:
            case NSURLErrorClientCertificateRejected:
            case NSURLErrorClientCertificateRequired:
                tError = kYQLS(@"无法连接到服务器，请检查你的网络或稍后重试");
                break;
            case NSURLErrorHTTPTooManyRedirects:
                tError = kYQLS(@"太多HTTP重定向，请检查你的网络或稍后重试");
                break;
                
            default:
                tError = kYQLS(@"系统繁忙，请稍后再试");
                break;
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        });
        if (failure) {
            failure([error code],tError);
        }
    }];
}

@end
